#include "DebugConsole.h"

CDebugConsole* CDebugConsole::m_pInstance = NULL;

//Read Function
unsigned int __stdcall ReadThis(void* that)
{
	CDebugConsole* console = CDebugConsole::GetInstance();

	while(true)
	{
		console->Read();
		
		if(console->ShutDownTime())
			break;

		Sleep(1);
	}

	return 1;
	
};

unsigned int __stdcall OutThis(void* that)
{
	CDebugConsole* console = CDebugConsole::GetInstance();

	while(true)
	{

		if(console->ShutDownTime())
			break;

		Sleep(1);
	}

	return 1;
	
};


// Proper Singleton
CDebugConsole::CDebugConsole() : iostream(NULL)
{
}

CDebugConsole::~CDebugConsole()
{

}

CDebugConsole* CDebugConsole::GetInstance()
{
	if (NULL == m_pInstance)
	{
		m_pInstance = new CDebugConsole();
	}
	return m_pInstance;
}

void CDebugConsole::Initialize()
{
	// Allocate the console window.
	if (AllocConsole())
	{
		m_hConsole		= GetStdHandle(STD_OUTPUT_HANDLE);
		m_hInputHandle	= GetStdHandle(STD_INPUT_HANDLE);
		
		m_bTimeToLeave = false;
		
		LockSection = new CRITICAL_SECTION();

		InitializeCriticalSection(LockSection);

		unsigned int ThreadId = 0;

		ThreadHandle = (HANDLE)_beginthreadex(NULL,0,&OutThis,NULL,0,&ThreadId);

	}

}

void CDebugConsole::ShutDown()
{
	LockIt();
		m_bTimeToLeave = true;
	UnLockIt();
	
	if(ThreadHandle != NULL)
		WaitForSingleObject(ThreadHandle,INFINITE);

	CloseHandle(ThreadHandle);

	LeaveCriticalSection(LockSection);
	
	if(LockSection)
		delete LockSection;
}
